package com.xhwl.centiotdata.handler.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.handler.alarm.AlarmHandler;
import com.xhwl.centiotdata.service.integrateconfig.AlarmIntegrationConfig;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import com.xhwl.common.dto.cent.alarm.tongtong.TongTongAlarmJson;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.alarm.AlarmLog;
import com.xhwl.common.pojo.cent.alarm.AlarmManagement;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.utils.ChkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author masiyuan
 * @since 2023年05月16日 09:05
 */

@Component
@Slf4j
public class TongTongReceiveHandler extends AlarmHandler {

    @Autowired
    AlarmIntegrationConfig alarmIntegrationConfig;


    @Override
    public void afterPropertiesSet() throws Exception {

    }


    public void tongTongAlarmReceive(String receiveContent, HttpServletResponse response) {
        response.setHeader("Content-Type","text/html;charset=utf-8");
        PrintWriter writer = null;
        log.info("====收到 通通高空抛物 告警消息 ===: {}", receiveContent);
        AlarmLog alarmLog = new AlarmLog();
        alarmLog.setTag("tongtong_alarm");
        alarmLog.setContent(receiveContent);
        alarmLog.setPushTime(new Date());
        centAlarmService.insert(alarmLog);

        Map<String, String> entries = redisTemplate.opsForHash().entries(RedisUtils.format(ProductEnum.TONGTONG.getId()));
        TongTongAlarmJson tongTongAlarmJson = JSONObject.parseObject(receiveContent, TongTongAlarmJson.class);

        String msgId = tongTongAlarmJson.getMsgId();
        String alarmType = tongTongAlarmJson.getMsgType();

        if(redisTemplate.opsForValue().get("alarm_tongtong_" + msgId) != null) {
            log.info("通通高空抛物告警消息重复： {}", msgId);
            try {
                writer = response.getWriter();
                writer.write(msgId.toCharArray());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                writer.close();
            }
            return;
        }

        List<String> thirdDeviceIdList = new ArrayList<>();
        thirdDeviceIdList.add(tongTongAlarmJson.getDeviceSerial());

        if(ChkUtil.isNotNull(entries.get(alarmType))) {
            DevicePageQuery devicePageQuery = new DevicePageQuery();
            devicePageQuery.setThirdDeviceIdList(thirdDeviceIdList);
            Page<DeviceDTO> deviceDTOPage = deviceCentService.pageDevice(null, devicePageQuery);
            DeviceDTO deviceDTO = Optional.ofNullable(deviceDTOPage).map(Page::getRecords)
                    .filter(item -> CollectionUtils.isNotEmpty(item))
                    .map(item -> item.get(0)).orElseThrow(() -> new BusinessException("====================》设备不存在《================"));

            AlarmManagement alarmManagement = new AlarmManagement();
            alarmManagement.setAlarmTime(new Date());
            alarmManagement.setDeviceId(deviceDTO.getId());
            alarmManagement.setProjectId(deviceDTO.getProjectId());
            alarmManagement.setAlarmInventoryCode(entries.get(alarmType));
            alarmManagement.setImgUrl(tongTongAlarmJson.getPicUrl());
            alarmManagement.setAlarmRemark("视频地址：" + tongTongAlarmJson.getVidUrl());
            alarmManagement.setThirdDeviceId(tongTongAlarmJson.getDeviceSerial());
            sendMq(AlarmConstant.TONGTONG_ALARM_TOPIC, alarmManagement);

            redisTemplate.opsForValue().set("alarm_tongtong_" + msgId, msgId, 1, TimeUnit.HOURS);
        } else {
            log.error("通通高空抛物告警类型未配置: {}", alarmType);
        }
        try {
            writer = response.getWriter();
            writer.write(msgId.toCharArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
}
